package vip.bblog.cunadmin.modules.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import vip.bblog.cunadmin.annotation.group.Update;
import vip.bblog.cunadmin.common.entity.BaseResult;
import vip.bblog.cunadmin.modules.system.entity.Wxuser;
import vip.bblog.cunadmin.modules.system.service.WxuserService;
import vip.bblog.cunadmin.util.HttpClientUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;


@Api(value = "wxuserAPI",tags = {"wxuserAPI"})
@Validated
@RestController
@RequestMapping("/wxuser")
public class WxuserController {
    @Autowired
    private WxuserService wxuserService;

    private String appid = "wx959527a9cb44eec4";
    private String appSecret = "2d1377ee9c0936894e6f907ccbe10361";
 

    @ApiOperation(value = "新增微信用户",notes = "新增微信用户")
    @PostMapping("/add")
    public BaseResult addwxuser(@Validated(Update.class) @RequestBody Wxuser params){
        boolean res = wxuserService.save(params);
        return BaseResult.success();
    }


    @ApiOperation(value = "删除微信用户",notes = "删除微信用户")
    @DeleteMapping("/{id}")
    public BaseResult deletewxuser(@PathVariable("id")Long id){
        boolean res = wxuserService.removeById(id);
        return BaseResult.success();
    }

    @ApiOperation(value = "获取用户信息",notes = "获取用户信息")
    @GetMapping("/getById/{id}")
    public BaseResult getById(@PathVariable("id")Long id){
        Wxuser wxuser = wxuserService.getById(id);
        return BaseResult.success(wxuser);
    }


    @ApiOperation(value = "修改微信用户",notes = "修改微信用户测试")
    @PostMapping("/edit")
    public BaseResult updatewxuser(@Validated(Update.class) @RequestBody Wxuser wxuser){
        boolean res = wxuserService.updateById(wxuser);
        return BaseResult.success();
    }

    @ApiOperation(value = "分页查询微信用户",notes = "分页查询微信用户")
    @GetMapping("/getByPage")
    public BaseResult pagewxuser(Wxuser params){
        Map<String, Object> byPage = wxuserService.getByPage(params);
        return BaseResult.success(byPage);
    }

    @RequestMapping("/login")
    @ResponseBody
    public BaseResult index(Wxuser user, HttpServletRequest request, HttpServletResponse response){
        String code = request.getParameter("code");
        String access_token_url  = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid="+appid+
                "&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";
        String json = HttpClientUtil.doGet(access_token_url);
        JSONObject jsonObj = JSON.parseObject(json);
        String openid = (String) jsonObj.get("openid");

        String access_token = (String) jsonObj.get("access_token");
        String getinfo = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid;
        String baseInfo = HttpClientUtil.doGet(getinfo);
        JSONObject baseinfoObj = JSON.parseObject(baseInfo);
        //判断openid是否存在
        Wxuser userByOpenid = wxuserService.getUserByOpenid(openid);

        user.setOpenid(openid);
        if(userByOpenid == null){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = df.format(new Date());
            user.setCtime(date);
            //添加
            wxuserService.save(user);
        }else{
            //修改
            user.setId(userByOpenid.getId());
            wxuserService.updateById(user);
        }
        System.out.println(baseinfoObj.toJSONString());
        return BaseResult.success(user);
    }

}
